#include "uartx.h"


char rxBufferData[RXTXBUFFERLEN];

// uart的选择,这里选择uart2
const uart_port_t uart_num = UART_NUM_2;


// uartx 接收数据
// 返回值: 接收数据的字节长度
int uartx_rx(void)
{
    int length = 0;
    // 清除接受缓存区中的数据
    memset(rxBufferData, 0, sizeof(rxBufferData));
    
    uint8_t* data = (uint8_t*)malloc(RXTXBUFFERLEN);

    length = uart_read_bytes(uart_num, data, RXTXBUFFERLEN, 200);
    if (length > 0) {
        memcpy(rxBufferData, data, length);
        ESP_ERROR_CHECK(uart_flush(uart_num)); // 读取数据后就清空FIFO 缓冲区
    }

    free(data);
    return length;
}

// uartx: 发送数据
// 返回值: 接收数据的字节长度
int uartx_tx(char* bufData)
{
    if(bufData == NULL){
        return -1;
    }

   int length = 0;

    // 硬件流控制
    ESP_ERROR_CHECK(uart_wait_tx_done(uart_num, 100)); // 等待TX FIFO缓冲区为空
    length = uart_write_bytes(uart_num, bufData, strlen(bufData)+1);
    if(length != 0){
        ESP_ERROR_CHECK(uart_flush(uart_num)); // 读取数据后就清空FIFO 缓冲区
    }
    vTaskDelay(1000 / portTICK_PERIOD_MS); // 延时10ms清除数据和接受数据

    return length;
}

// uarx 配置
void uartx_config(int baudSize)
{
    uart_config_t uart_config = {
        .baud_rate = baudSize,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = flowCtrl(FLOWCTRLFLAG),
        .rx_flow_ctrl_thresh = 122,
    };

    // Configure UART parameters
    ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));

#if FLOWCTRLFLAG
    // 硬件流控制
    // Set UART pins(TX: IO16, RX: IO17, RTS: IO18, CTS: IO19)
    ESP_ERROR_CHECK(uart_set_pin(uart_num, uart2_tx_gpio, \
        uart2_rx_gpio, RTS, CTS));

    // Setup UART buffered IO with event queue
    QueueHandle_t uart_queue;
    // Install UART driver using an event queue here
    ESP_ERROR_CHECK(uart_driver_install(uart_num, RXTXBUFFERLEN*2, \
                                            RXTXBUFFERLEN*2, 10, &uart_queue, 0));
    
#else 
    // 软件流控制
    ESP_ERROR_CHECK(uart_set_pin(uart_num, uart2_tx_gpio, \
        uart2_rx_gpio, RTS, CTS));
    // 配置通讯的buffer
	ESP_ERROR_CHECK(uart_driver_install(uart_num, RXTXBUFFERLEN*2, \
        RXTXBUFFERLEN*2, 0, NULL, 0));

#endif   
}

/* 测试代码
#include <stdio.h>
#include "uartx.h"

void app_main(void)
{
    uartx_config(115200);
#if 0
    // 发送数据测试
    int i = 0;

    while(i != 100){
        char* buf = "zx is xiaokeai\r\n";
        int length = uartx_tx(buf); 
        printf("length:%d\n", length);
        i++;
    }
#else
    // 接收数据测试
    int i = 0;
    while(i++ != 100){
        int length = uartx_rx(); 
        if(length > 0){
            printf("i:%d, length:%d, recvdata: %s\n", i, length, rxBufferData);
        }
    }
#endif
   
}

*/


